﻿using MailKit.Net.Smtp;
using MimeKit;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Storage;

namespace Mail_Box_Net_Disk.PublicTools
{
    class smtp
    {
        public static string IMAPServer = "imap.qq.com";
        public static string SMTPServer = "smtp.qq.com";
        public static int IMAPPort = 993;
        public static int SMTPPort = 465;
        public static string account = "";
        public static string password = "";
        public static bool isSSL = true;
        public static int fileSplit = 10;

        public static async Task UploadFiles(StorageFile file)
        {
            string hash = file.GetHashCode().ToString();
            var message = new MimeMessage();
            message.From.Add(new MailboxAddress("File Uploader", account));
            message.To.Add(new MailboxAddress(account, account));
            message.Subject = "mailbox net disk file:" + hash + ",File name:" + file.Name;

            StorageFolder folder = ApplicationData.Current.TemporaryFolder;
            StorageFile newfile = await file.CopyAsync(folder, file.Name, NameCollisionOption.GenerateUniqueName);

            var body = new TextPart("plain")
            {
                Text = 
@"WORNING:This e-mail was sent by mailbox net disk,don't delete this.
注意：这封邮件由邮箱网盘工具发送，请勿删除。
file hash:" + hash
            };

            // create an image attachment for the file located at path
            var attachment = new MimePart()
            {
                ContentObject = new ContentObject(File.OpenRead(newfile.Path), ContentEncoding.Default),
                ContentDisposition = new ContentDisposition(ContentDisposition.Attachment),
                ContentTransferEncoding = ContentEncoding.Base64,
                FileName = newfile.Name
            };

            // now create the multipart/mixed container to hold the message text and the
            // image attachment
            var multipart = new Multipart("mixed");
            multipart.Add(body);
            multipart.Add(attachment);

            // now set the multipart/mixed as the message body
            message.Body = multipart;

            using (var client = new SmtpClient())
            {
                client.Connect(SMTPServer, SMTPPort, isSSL);

                // Note: since we don't have an OAuth2 token, disable
                // the XOAUTH2 authentication mechanism.
                client.AuthenticationMechanisms.Remove("XOAUTH2");

                // Note: only needed if the SMTP server requires authentication
                client.Authenticate(account, password);

                client.Send(message);
                client.Disconnect(true);
            }
        }
    }
}
